package chapter14;

import java.io.*;
import java.util.Map;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/22 15:46
 */
public class StudentsDB {
    private static IBasicDB db;

    static {
        try {
            db = new BasicDB("./", "students");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Student getStudentByName(String name) throws IOException {
        byte[] dat = db.get(name);
        return fromByte(dat);
    }

    public static void saveStudents(Map<String, Student> students) throws IOException {
        for (Map.Entry<String, Student> entry : students.entrySet()) {
            db.put(entry.getKey(), toBytes(entry.getValue()));
        }
        db.close();
    }

    private static byte[] toBytes(Student student) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(out);
        dout.writeUTF(student.getName());
        dout.writeInt(student.getAge());
        dout.writeDouble(student.getScore());
        return out.toByteArray();
    }

    private static Student fromByte(byte[] data) throws IOException {
        if (data == null || data.length == 0) {
            return null;
        }
        ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
        DataInputStream dataInputStream = new DataInputStream(inputStream);
        String name = dataInputStream.readUTF();
        int age = dataInputStream.readInt();
        double score = dataInputStream.readDouble();

        return new Student(name, age, score);
    }

    public static void main(String[] args) {

        try {
            Student student = getStudentByName("张三");
            System.out.println(student.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        /*List<Student> students = Arrays.asList(new Student[]{
                new Student("张三", 18, 89.87),
                new Student("李四", 17, 90.1)
        });

        Map<String,Student> map = students.stream().collect(Collectors.toMap(Student::getName,student -> student));

        try {
            saveStudents(map);
        } catch (IOException e) {
            e.printStackTrace();
        }*/
    }
}
